<template>
  <div class="app-container">
    <div style="font-size: 25px;">销售详情</div>
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-col :span="8">
          <el-form-item label="销售单号" prop="saleNumber" style="width: 400px" :rules="[{ required: true ,message: '请输入销售单号'}]">
            <el-input v-model="form.saleNumber" placeholder="请输入销售单号" maxlength="15" required="required" disabled/>
          </el-form-item>
        </el-col>
      <el-col :span="8">
        <el-form-item label="发货单号" style="width: 400px" prop="shipmentNum">
          <el-input v-model="shipmentNo"
                    placeholder="发货单号"
                    maxlength="15"
                    :disabled="true"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="客户" prop="customerId" style="width: 400px" :rules="[{ required: true ,message: '请选择客户'}]">
            <el-select
              disabled
              v-model="form.customerId"
              placeholder="请选择客户"
              clearable
              size="small"
              style="width: 100%"
              @change="getInfo(form.customerId)"
            >
              <el-option
                v-for="dict in customerList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="客户手机" style="width: 400px"  prop="customerPhone">
            <el-input disabled v-model="customerTelephone" placeholder="请输入客户手机"/>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="收获地址" style="width: 400px"  prop="customerAddress">
            <el-cascader
              disabled
              style="width: 100%"
              expand-trigger="hover"
              ref="cascaderAddr"
              size="small"
              :options="options"
              v-model="selectedOptions"
              @change="handleChange">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="详细地址" style="width: 400px"  prop="detailedAddress">
            <el-input v-model="detailedAdd" disabled placeholder="请输入详细地址"/>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="固定电话" style="width: 400px"  prop="fixedTelephone">
            <el-input v-model="form.fixedTelephone" disabled placeholder="请输入固定电话"/>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="收款方式" style="width: 400px"  prop="paymentMethod">
            <el-select v-model="form.paymentMethod" disabled placeholder="请选择收款方式" style="width: 100%" clearable>
              <el-option
                v-for="dict in dict.type.erp_payment_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="备注" style="width: 400px"  prop="customerContact">
            <el-input v-model="form.customerContact" disabled placeholder="请输入简要备注" maxlength="255"/>
          </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="订单状态" style="width: 400px" >
          <span style="display:inline-block;width:200px;font-weight:bold;">
            {{auditStatus}}
          </span>
        </el-form-item>
      </el-col>
          <el-table :data="addGoodsList" default-expand-all show-summary :summary-method="getSummaries"  >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table v-show="props.row.goodWarehouseList.length != 0" v-bind:data="props.row.goodWarehouseList"
                          :default-expand-all="true" show-summary :summary-method="getSummaries" :show-header="true"
                          :header-cell-style="{background:'#FFFFFF',color:'#606266'}">
                  <el-table-column prop="warehouseName" align="center" label="发货仓库"/>
                  <el-table-column prop="goodsNumber" align="center" label="发货数量"/>
                  <el-table-column prop="returnGoodNumber" align="center" label="退货数量"/>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="商品ID" align="center" prop="id"/>
            <el-table-column label="商品名称" align="center" prop="name"/>
            <el-table-column label="分类" align="center" prop="categoryName"/>
            <el-table-column label="品牌" align="center" prop="brandName"/>
            <el-table-column label="单位" align="center" prop="companyName"/>
            <el-table-column label="成本单价" align="center" prop="cost"/>
            <el-table-column label="销售单价" align="center" prop="price">
              <div class="item" slot-scope="scope">
                <el-input class="item__input" disabled v-model="scope.row.price" placeholder="请输入价格" size="mini"
                          style="width:100px" @input="handleEdit(scope.$index, scope.row)"></el-input>
              </div>
            </el-table-column>
            <el-table-column label="销售数量" align="center" prop="quantity">
              <div class="item" slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" disabled controls-position="right" :min="0" size="mini"
                                 style="width:100px" @input="handleEdit(scope.$index, scope.row)"/>
              </div>
            </el-table-column>
            <el-table-column label="销售总价" align="center" prop="oneGoodPrice">
              <div class="item" slot-scope="scope">
                <el-input class="item__input" disabled v-model="scope.row.oneGoodPrice" placeholder="销售总价" size="mini"
                          style="width:100px" readonly="readonly"></el-input>
              </div>
            </el-table-column>
          </el-table>

    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button
        type="primary"
        v-if=saleType
        @click="handleAdd(0)"
      >确认订单
      </el-button>
      <el-button
        type="primary"
        v-if= sellType
        @click="handleAdd(1)"
      >取消确认
      </el-button>
      <el-button type="primary" @click="submitForm">返回</el-button>
    </div>
  </div>

</template>

<script>

import {getCustomer, listCustomer} from "@/api/erp/customer";
import {CodeToText, regionData} from "element-china-area-data";
import {addGoods, listGoods} from "@/api/erp/goods";
import {listCategory} from "@/api/erp/category";
import {listBrand} from "@/api/erp/brand";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {addSale, addSaleGood, delSale, delSaleGood, getSale, updateSale, updateSaleType} from "@/api/erp/sale";

let stream = require('stream')

export default {
  name: "sale",
  components: {Treeselect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      //
      shipmentNo:null,
      //订单状态
      auditStatus: null,

      saleType: false,

      sellType:false,
      //删除参数
      delGoodData: {},

      sellId: null,
      //品牌列表
      brandList: [],
      //elementUi地区数据
      options: regionData,
      //分类列表
      categoryOptions: [],
      //客户列表
      customerList: [],
      //客户电话
      customerTelephone: null,
      //客户地址
      detailedAdd: null,
      // 商品信息表格数据
      goodsList: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      //客户省市区
      selectedOptions: [],
      // 总条数
      total: 0,
      //表单参数
      form: {},
      //商品表单参数
      goodsForm: {},
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //表单校验
      rules: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
      },
    };
  },
  created() {
    const saleId = this.$route.query.id
    this.sellId = saleId;
    if (saleId) {
      this.getList(saleId);
    }
    this.selectCustomer();
  },

  methods: {
    //刷新页面数据
    getList(saleId) {
      getSale(saleId).then(response => {
        this.form = response.data
        this.customerTelephone = response.data.customerPhone
        this.detailedAdd = response.data.detailedAddress
        this.selectedOptions = [response.data.province.toString(), response.data.city.toString(), response.data.area.toString()]
        this.addGoodsList = response.data.goodsList;
        this.shipmentNo = response.data.shipmentNum
        if (response.data.type == 1){
           this.saleType = true
          this.sellType = false
        }
        if (response.data.type == 0){
          this.saleType = false
          this.sellType = true
          this.auditStatus = "已确认"
        }
        if (response.data.type == 1){
          this.auditStatus = "未确认"
        }
        if (response.data.type == 2){
          this.auditStatus = "发货出库"
        }
        if (response.data.type == 3){
          this.auditStatus = "确认收货"
        }
      })
    },
    // 审核订单按钮操作
    handleAdd(type) {
      let id  = null;
      id = this.sellId;
      var _that = this
      this.$modal.confirm('是否确认销售订单已无误!').then(function() {
        updateSaleType(id,type).then(response =>{
          if (response.code == 200){
            _that.getList(_that.sellId);
          }
        })
      }).then(() => {
        this.$modal.msgSuccess("操作成功")
        _that.close();
      }).catch(() => {});
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 查询商品列表
    getGoodList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取客户信息
    getInfo(row) {
      const id = row
      getCustomer(id).then(response => {
        this.customerTelephone = response.data.phone
        this.detailedAdd = response.data.detailedAddress
        this.form.province = response.data.province
        this.form.city = response.data.city
        this.form.area = response.data.area
        this.form.detailedAddress = response.data.detailedAddress
        this.form.customerAddress = response.data.customerAddress
        this.selectedOptions = [response.data.province.toString(), response.data.city.toString(), response.data.area.toString()]
      });
    },
    //查询客户列表
    selectCustomer() {
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
      });
    },
    //商品总价计算
    handleEdit(index, row) {
      if (row.quantity && row.price) {
        row.oneGoodPrice = Number(row.quantity) * Number(row.price)
      }
    },
    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "oneGoodPrice" ||
          column.property === "returnGoodNumber" ||
          column.property === "goodsNumber"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '' ;
        }
      });
      return sums;
    },
    /*node分类节点*/
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    //elementUi选择地址
    handleChange(value) {
      this.selectedOptions = value
      var name = ''
      this.selectedOptions.map(item =>
        name += CodeToText[item] + '') //将省市区三个拼接一起
      this.form.province = value[0];
      this.form.city = value[1];
      this.form.area = value[2];
      this.form.customerAddress = name;
    },
    //返回按钮
    submitForm() {
      this.close();
    },
    //返回上一页商品列表页
    close() {
      this.$router.push({path: '/saleList'});
    },
  }
}

</script>

